<?php

namespace Yongf\Utils;

class UFunc
{

    /**
     * @Description：保留2位小数
     * @Docs：
     *
     * @param     $num
     * @param int $digit
     *
     * @return float
     * @Author：雍飞
     * @Date：2022/6/23 14:16
     */
    public static function toFixed($num, int $digit = 2): float
    {
        if (!is_numeric($num)) {
            return 0;
        }
        return floatval(sprintf("%.{$digit}f", $num));
    }

    /**
     * @Description：批量保留2位小数
     * @Docs：
     *
     * @param     $arr
     * @param     $keys
     * @param int $digit
     *
     * @return void
     * @Author：雍飞
     * @Date：2022/6/23 14:16
     */
    public static function toFixers(&$arr, $keys, int $digit = 2)
    {
        if (is_object($arr)) {
            foreach ($keys as $key) {
                if (isset($arr->{$key})) {
                    $arr->{$key} = self::toFixed($arr->{$key}, $digit);
                }
            }
        } else {
            foreach ($arr as $key => &$value) {
                if (in_array($key, $keys)) {
                    $value = self::toFixed($value, $digit);
                }
            }
            unset($value);
        }
    }


    /**
     * @Description：生成唯一订单号
     * @Docs：
     *
     * @return string
     * @Author：雍飞
     * @Date：2022/6/23 14:38
     */
    public static function uniqOrderNum(): string
    {
        $orderIdMain = date('YmdHis', time()) . rand(1000000000, 9999999999);
        //订单号码主体长度
        $order_id_len = strlen($orderIdMain);
        $orderIdSum   = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $orderIdSum += (int)(substr($orderIdMain, $i, 1));
        }
        return $orderIdMain . str_pad((100 - $orderIdSum % 100) % 100, 2, '0', STR_PAD_LEFT);
    }

    /**
     * @Description：获取客户端访问ip
     * @Docs：
     *
     * @return mixed|string
     * @Author：雍飞
     * @Date：2022/6/23 14:47
     */
    public static function getClientIp()
    {
        //验证HTTP头中是否有REMOTE_ADDR
        if (!isset($_SERVER['REMOTE_ADDR'])) {
            return '127.0.0.1';
        }
        $clientIp = $_SERVER['REMOTE_ADDR'];

        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])
            && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
            foreach ($matches[0] as $xip) {
                if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                    $clientIp = $xip;
                    break;
                }
            }
        } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && filter_var($clientIp, FILTER_VALIDATE_IP)) {
            $clientIp = $_SERVER['HTTP_CLIENT_IP'];
        }

        return $clientIp;
    }





}